package com.epoch.platform.sys.org.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.epoch.base.tree.TreeUtil;
import com.epoch.base.tree.ZrTreeBean;
import com.epoch.platform.sys.org.dao.SysOrg;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

public class SysOrgService {
	
	public List<SysOrg> findSysOrgList(Kv params) {
		SqlPara sqlPara = Db.getSqlPara("systemManage.findSysOrgList",params);
		if(null == params.get("parent_id") ) {
			sqlPara = Db.getSqlPara("systemManage.findSysOrgListOne");
		}
		List<SysOrg> sysMenuList = SysOrg.dao.find(sqlPara);
		return sysMenuList;
	}
	
	public List<SysOrg>  getTreeOrgList(Kv params){
		List<SysOrg> sysOrgList = this.findSysOrgList(params);
		return sysOrgList;
	}
	
	public List<ZrTreeBean>  getAllTreeOrgList(){
		SqlPara sqlPara = Db.getSqlPara("systemManage.findAllSysOrgList");
		List<SysOrg> sysOrgList = SysOrg.dao.find(sqlPara);
		List<ZrTreeBean> allTreeList = new ArrayList<ZrTreeBean>();
		for (SysOrg sysOrg : sysOrgList) {
			ZrTreeBean tree = new ZrTreeBean();
			tree.setId(sysOrg.getStr(SysOrg.ID));
			tree.setParentId(sysOrg.getStr(SysOrg.PARENT_ID));
			tree.setName(sysOrg.getStr(SysOrg.ORG_NAME));
			tree.setCode(sysOrg.getStr(SysOrg.ORG_CODE));
			tree.setComments(sysOrg.getStr(SysOrg.COMMENTS));
			allTreeList.add(tree);
		}
		return TreeUtil.getTreeList(allTreeList);
	}
	
	public boolean checkCodeExist(String code) {
		Kv params = Kv.create();
		params.set("org_code",code);
		SqlPara sqlPara = Db.getSqlPara("systemManage.findOrgCodeCount",params);
		SysOrg sysOrg = SysOrg.dao.findFirst(sqlPara);
		int count = sysOrg.getInt("COUNT");
		System.out.println(count);
		if(count == 0) {
			return true;
		}
		return false;
		
	}
	
	public boolean checkMenuIsLeaf(String parentId) {	
		Record record = Db.findFirst("SELECT COUNT(*) FROM SYS_ORG WHERE PARENT_ID = '"+parentId+"'");
		Integer count = record.getInt("count(*)");
		if(count == 0){
			return true;
		}
		return false;
	}
}
